<template>
    <div>
      <!-- 搜索条件 -->
      <el-card v-show="showQueryForm" class="form-card">
        <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="82px">
                  <QueryFormItem label="登录时间">
          <el-date-picker v-model="pickerDate"
                          :shortcuts="pickerShortcuts"
                          class="card-header-extra-action"
                          clearable
                          end-placeholder="结束日期"
                          format="YYYY-MM-DD"
                          start-placeholder="开始日期"
                          type="daterange"
                          value-format="YYYY-MM-DD"/>
        </QueryFormItem>
            <template #control>
            <el-button icon="RefreshRight" type="primary" plain round @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
            <el-button icon="Search" type="primary" round @click="handleSearch">{{ $t('form.search') }}</el-button>
          </template>
        </QueryForm>
      </el-card>

      <!-- 列表数据 -->
      <el-card class="content-card">
        <!-- 工具栏 -->
        <table-toolbar v-model:columns="columns"
                       v-model:show-query-form="showQueryForm"
                       v-model:size="size"
                       v-model:stripe="stripe"
                       @refresh="handleSearch">
        </table-toolbar>
        <el-button v-permission="'manager:info:create'" icon="Plus" round type="primary" @click="handleFormShow(1)">新增商务</el-button>
        <!-- 列表记录 -->
        <div class="table-wrapper">
          <!-- 列表数据 -->
          <el-table ref="tableRef"
                    v-loading="loading"
                    :data="tableData"
                    :size="size"
                    :stripe="stripe"
                    row-key="id"
                    show-overflow-tooltip
                    @select="handleSelectChange"
                    @select-all="handleSelectAll"
                    @sort-change="handleSortChange">
            <template #empty>
              <el-empty class="table-empty" description="暂无数据"/>
            </template>

            <table-column :columns="columns">
              <template #target_uid="scope">
                <UserInfoLink :user-id="scope.row.target_uid"/>
              </template>

              <template #status="scope">
                <DictTag v-model="scope.row.status" :circle="false" dict-type="manager_status"/>
              </template>

              <template #operations="scope">
                <el-space :size="1" :spacer="spacer">
                  <el-button v-permission="'manager:info:list'"  link type="primary" @click="handleInfo(scope.row)">客户详情</el-button>
                  <el-button v-permission="'manager:info:update'"  link type="primary" @click="handleFormShow(2,scope.row)">编辑</el-button>
                <el-button v-permission="'manager:info:delete'"  link type="danger" @click="handleAudit(scope.row)">删除</el-button>
                </el-space>
              </template>

            </table-column>
          </el-table>

          <!-- 分页操作 -->
          <el-pagination v-if="totalCount > 0"
                         :current-page="pageQuery.pageNum"
                         :page-size="pageQuery.pageSize"
                         :page-sizes="pageSizes"
                         :total="totalCount"
                         background
                         class="table-pagination"
                         layout="total, sizes, prev, pager, next"
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"/>
        </div>
      </el-card>

    </div>
  </template>

  <script lang="tsx" setup>
  import { computed, h, onBeforeMount, reactive, ref ,onActivated} from 'vue';
  import useLoading from '@/hooks/use-loading';
  import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
  import TableToolbar from '@/components/table-toolbar/index.vue';
  import {ElDivider, ElLoading, ElMessage, ElMessageBox, ElNotification, TableInstance} from 'element-plus';
  import useTable from '@/hooks/use-table.ts';
  import { hasPermission } from '@/utils/permission.ts';
  import { computedOperateWidth ,pickerShortcuts} from '@/utils';
  import { DictTag } from '@/components/dict-tag';
  import useTableSelection from '@/hooks/use-table-selection.ts';
  import { QueryFormItemRule } from '@/components/query-form/constants.ts';
  import { UserInfoLink } from '@/components/user-info-link';
  import { QueryForm, QueryFormItem } from '@/components/query-form';
  import { MANAGERList,MANAGERDelete } from "@/api/api-manager.ts";
  import { timeStamp } from '@/utils/validate';
  import { useRouter } from 'vue-router';
  const spacer = h(ElDivider, { direction: 'vertical' })
  defineOptions({name: 'partner-give-away-list'});
  onActivated(() => {
  if (history.state.params && parseInt(history.state.params.refresh || '0') > 0) {
    handleSearch();
  }
});
  // 查询
  const queryFormData = reactive({
    name: undefined,
    date: undefined,
  });
  const queryFormRef = ref<InstanceType<typeof QueryForm>>();
  const queryFormItems = ref<QueryFormItemRule[]>([
    {type: 'input', prop: 'name', label: '商务姓名', placeholder: '请输入商务姓名', clearable: true,},
  ]);

  // 列表数据
  const tableRef = ref<TableInstance>();
  const tableData = ref<any[]>([]);
  const totalCount = ref(0);
  const pickerDate = ref([]);
  // 操作区域宽度计算
// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('manager:info:list')) count += 2
  if (hasPermission('manager:info:update')) count += 1
  if(hasPermission('manager:info:delete')) count += 1
  return computedOperateWidth(count);
});

  // 列设置
  const columns = ref<TableColumnData[]>([
    {prop: 'id', label: '编号', width: 105, align: 'center', },
    {prop: 'name', label: '商务姓名', width: 150, align: 'center', },
    {prop: 'phone', label: '联系人电话', width: 120, align: 'center', },
    {prop: '', label: '客户数量', minWidth: 160, align: 'center', render: (scope, val) => <span>{val || '-'}</span>},
    {prop: '', label: '累计首单流水', width: 110, align: 'center',render: (scope, val) => <span>{val || '-'}</span> },
    {prop: '', label: '累计代付流水', width: 180, align: 'center',  render: (scope, val) => <span>{val || '-'}</span>},
    {prop: 'status', label: '状态', width: 180, align: 'center', },
    {prop: 'create_time', label: '创建时间', width: 180, align: 'center', render: (scope, val) => <span>{timeStamp(val) || '-'}</span>},
  ]);

  onBeforeMount(() => {
    if (operateWidth.value > 0) {
      columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'center', headerAlign: 'center'},)
    }
  });

  const [loading, setLoading] = useLoading(false);
  const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true, true);
  const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState;
  const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods;
  const {handleSelectChange, handleSelectAll, multipleSelection, clearSelection} = useTableSelection(tableData, tableRef);


  // 数据查询
  const fetchDataList = async () => {
    setLoading(true);
    try {
        queryFormData.date = pickerDate.value && pickerDate.value.length == 2 ? pickerDate.value[0] + '~' + pickerDate.value[1] : undefined
      // 查询数据
      const {body} = await MANAGERList({
        action:'list',
        page: pageQuery.pageNum,
        size: pageQuery.pageSize,
        ...queryFormData,
      });
      console.log(queryFormData.date);
      // 结果转换
      tableData.value = body.list;
      totalCount.value = body.pages.count;
    } catch (err) {
    } finally {
      setLoading(false);
    }
  };

  // 刷新数据
  const handleSearch = () => {
    fetchDataList();
  };

  // 重置查询条件
  const handleResetQueryForm = () => {
    pickerDate.value = [];
    clearSelection();
    handleResetForm();
  };

  /** 添加/修改操作 */
const router = useRouter();
  const handleFormShow = (mode: number, row?: any) => {
    let itemId = row ? row.id : 0
if (mode === 1) { // 新增
    router.push({path: '/manager/create/' + itemId})
  } else if (mode === 2) { // 编辑
    router.push({path: '/manager/update/' + itemId})
  }
  };

  /** s删除操作 */
  const handleAudit = (row: any) => {
    ElMessageBox.confirm(
      '是否确定删除此商务?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(({value}) => {
      const loading = ElLoading.service({
        lock: true,
        text: '正在提交中...',
        background: 'rgba(0, 0, 0, 0.2)'
      })
      let params = {id: row.id,action:'delete'};
      // 提交数据
      MANAGERDelete(params).then(response => {
        // 提示信息
        ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
        // 刷新数据
        handleSearch();
      }).finally(() => loading.close())
    }).catch(() => {

    });
  };
  // 客户详情
  const handleInfo=(row:any)=>{
    ElMessage('暂未开通')
  }

  </script>

  <style lang="scss" scoped>

  </style>
